import requests
import json
import execjs

# 读取JS代码
with open("xiniu.js", "r", encoding="utf-8") as f:
    js_code = f.read()

# 编译JS代码
ctx = execjs.compile(js_code)

# 请求头和cookies
headers = {
    "accept": "application/json",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7",
    "cache-control": "no-cache",
    "content-type": "application/json",
    "origin": "https://www.xiniudata.com",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://www.xiniudata.com/industry/newest?from=data",
    "sec-ch-ua": '"Microsoft Edge";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0",
}

cookies = {
    "Hm_lvt_42317524c1662a500d12d3784dbea0f8": "1750911243",
    "HMACCOUNT": "7CBD934A28002CBF",
    "btoken": "KU7VN04Y3A0IOM951SROW95VZC2G3801",
    "Hm_lpvt_42317524c1662a500d12d3784dbea0f8": "1750911333",
}

# API接口
url = "https://www.xiniudata.com/api2/service/x_service/person_industry_list/list_industries_by_sort"

# 构建payload
payload = {
    "sort": 1,
    "start": 100,
    "limit": 20,
}

# 使用JS函数生成加密payload和签名
encrypted_payload = ctx.call("get_encrypted_payload", payload)
signature = ctx.call("get_sig", payload)

# 构建请求数据
request_data = {
    "payload": encrypted_payload,
    "sig": signature,
    "v": 1,
}

print(f"Generated payload: {encrypted_payload}")
print(f"Generated signature: {signature}")

# 发送请求
response = requests.post(
    url,
    headers=headers,
    cookies=cookies,
    data=json.dumps(request_data, separators=(",", ":")),
)

print(f"Response status: {response.status_code}")

if response.status_code == 200:
    response_data = response.json()
    encrypted_data = response_data.get("d", "")

    if encrypted_data:
        # 使用JS函数解密响应数据
        decrypted_data = ctx.call("dec_resp", encrypted_data)
        print("Decrypted response:")
        print(json.dumps(decrypted_data, indent=2, ensure_ascii=False))
    else:
        print("No encrypted data found in response")
        print(response_data)
else:
    print(f"Request failed: {response.text}")
